package com.yidao.user.controller;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.yidao.core.controller.BaseController;
import com.yidao.user.domain.User;
import com.yidao.user.service.UserService;

@Controller
@RequestMapping("/users")
public class UserController extends BaseController{

	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/edit", method= RequestMethod.GET)
    public ModelAndView edit() {
		
		User user = super.getCurrentUser();
		
		System.out.println("user:" + user.toString());
		
		ModelAndView mv = new ModelAndView();
		mv.addObject("user", user);
		mv.setViewName("/users/edit");
		return mv;
    }
	
	@RequestMapping(value="/save", method = RequestMethod.POST)
    public ModelAndView save(@ModelAttribute("user") @Valid User user, 
    							BindingResult result) {
        if (result.hasErrors()) {
        	System.out.println("===field error here.===");
        	for(FieldError fieldError:result.getFieldErrors()){
        		System.out.println(fieldError.getCode());
        		System.out.println(fieldError.getField());
        		System.out.println(fieldError.getDefaultMessage());
        	}
        	ModelAndView mv = new ModelAndView();
    		mv.addObject("fieldErrors", result.getFieldErrors());
        	mv.addObject("user", new User());
    		mv.setViewName("/customers/edit");
    		return mv;
        }
        
        if(user.getId() == null){
        	userService.create(user);
        }else{
        	Long id = user.getId();
        	User destUser = userService.getById(id);
        	
        	//destUser.setUsername(user.getUsername());
        	destUser.setEmail(user.getEmail());
        	
        	userService.update(destUser);
        }
        return edit();
    }
	
	@RequestMapping(value = "/setting", method= RequestMethod.GET)
    public ModelAndView setting() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/users/setting");
		return mv;
    }
	
	@RequestMapping(value = "/password", method= RequestMethod.GET)
    public ModelAndView password() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/users/password");
		return mv;
    }
	
	@RequestMapping(value = "/password", method= RequestMethod.POST)
    public ModelAndView savePassword(	@RequestParam("oldPassword") String oldPassword,
    									@RequestParam("newPassword1") String newPassword1,
    									@RequestParam("newPassword2") String newPassword2
    ) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/users/password");
		List<ObjectError> errors = new ArrayList<ObjectError>();
		mv.addObject("errors",errors);
		
		//check password.
		if(StringUtils.isEmpty(oldPassword)){
			ObjectError error1 = new ObjectError("oldPassword","Old password can't be empty.");
			errors.add(error1);
			return mv;
		}
		if(StringUtils.isEmpty(newPassword1)){
			ObjectError error1 = new ObjectError("newPassword1","New password1 can't be empty.");
			errors.add(error1);
			return mv;
		}
		if(StringUtils.isEmpty(newPassword2)){
			ObjectError error2 = new ObjectError("newPassword2","New password2 can't be empty.");
			errors.add(error2);
			return mv;
		}
		if(!newPassword1.equals(newPassword2)){
			ObjectError error2 = new ObjectError("newPassword2","Password1 not equals password2.");
			errors.add(error2);
			return mv;
		}
		
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		String userName = "";
		if (principal instanceof UserDetails) {
			userName = ((UserDetails)principal).getUsername();
		} else {
			userName = principal.toString();
		}
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		//change password here.
		try{
			userService.changePassword(userName, oldPassword, newPassword1);
		}catch(Exception e){
			ObjectError error = new ObjectError("oldPassword","Password error.");
			errors.add(error);
			e.printStackTrace();
		}
		return mv;
    }
	
	@RequestMapping("/")
    public ModelAndView main() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/users/main");
		return mv;
    }
}
